import { ref } from 'vue'

function useInteractive() {
  const middleLeftStyle = ref(null)
  const middleRightStyle = ref(null)
  const currentView = ref('cd')
  let touchInfo = {}

  function onTouchStart(e) {
    touchInfo = {}
    touchInfo.startX = e.touches[0].pageX
    touchInfo.startY = e.touches[0].pageY
    touchInfo.directionLocked = ''
  }

  function onTouchMove(e) {
    const deltaX = e.touches[0].pageX - touchInfo.startX
    const deltaY = e.touches[0].pageY - touchInfo.startY

    const absDeltaX = Math.abs(deltaX)
    const absDeltaY = Math.abs(deltaY)

    if (!touchInfo.directionLocked) {
      touchInfo.directionLocked = absDeltaX > absDeltaY ? 'h' : 'v'
    }
    if (touchInfo.directionLocked === 'v') {
      return
    }

    const lyricStart = currentView.value === 'cd' ? 0 : -window.innerWidth

    const moveDistance = Math.min(
      0,
      Math.max(-window.innerWidth, lyricStart + deltaX)
    )
    touchInfo.movePercent = moveDistance / innerWidth

    const opacity = 1 + touchInfo.movePercent

    middleRightStyle.value = {
      transform: `translate3d(${moveDistance}px, 0, 0)`
    }
    middleLeftStyle.value = {
      opacity
    }
  }

  function onTouchEnd() {
    if (touchInfo.directionLocked === 'v') {
      return
    }
    if (currentView.value === 'cd' && touchInfo.movePercent <= -0.15) {
      currentView.value = 'lyric'
    } else if (
      currentView.value === 'lyric' &&
      touchInfo.movePercent >= -0.85
    ) {
      currentView.value = 'cd'
    }
    middleRightStyle.value = {
      transform: `translate3d(${
        currentView.value === 'cd' ? 0 : -window.innerWidth
      }px, 0, 0)`,
      transitionDuration: '300ms'
    }

    middleLeftStyle.value = {
      opacity: currentView.value === 'cd' ? 1 : 0,
      transitionDuration: '300ms'
    }
  }

  return {
    middleLeftStyle,
    middleRightStyle,
    onTouchStart,
    onTouchMove,
    onTouchEnd,
    currentView
  }
}

export default useInteractive
